#!/bin/bash
# @Author: leiwang
# @Date:   2018-10-08 12:25:43
# @Last Modified by:   leiwang
# @Last Modified time: 2018-11-02 15:31:28
# 通过进程名结束进程monitor，通过进程父子关系结束agent

export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin:/sbin:/bin:${PATH}
# 可执行文件名配置
monitor="dbMonitor"

# 结束异常检查
checkUser(){
  for i in `groups `; do
    if [ $i == "root" ]; then
      return 1
    fi
  done
  return 0
}
checkUser
ret=`echo $?`
if [ $ret != 1 ];then
    echo "WARN: User is not root!"
fi

# 动态获取脚本文件所在绝对路径
RUN_PATH=`cd $(dirname $0); pwd -P`

# 杀死进程，根据进程命令，获取进程id，传SIGTERM信号

pids=$(ps -ef | grep ${RUN_PATH}/${monitor}| grep -v grep |awk '{print $2}')
for pid in ${pids}
do
    childpids=$(ps -ef | awk '{if($3==pid)print $2}' pid=$pid)

    echo  "kill process $pid"
    kill -9 $pid 1>/dev/null 2>/dev/null

    for childpid in ${childpids}
    do
        echo  "kill process $childpid"
        kill $childpid 1>/dev/null 2>/dev/null
        sleep 1
        kill -9 $childpid 1>/dev/null 2>/dev/null  
    done
done

# 检查结果
if [ "`ps -ef |grep ${RUN_PATH}/${monitor}|grep -v grep |wc -l|tr -d ' '`" -gt "0" ];then
    echo "Stop dbagent failed"
else
    echo "Stop dbagent success"
fi
